
import React, { Component, createRef } from 'react'
import { DownOutlined, PlusOutlined, ExclamationCircleOutlined, MinusOutlined } from '@ant-design/icons';
import { Button, Space, Dropdown, Menu, message, Modal, Select } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import MotionLayout from '@/layouts/MotionLayout';
import { UserAdd, UserList, UserDel, UserRoleAdd, UserEditWithRole, BaseRoleList, UserRoleList } from "@/services/sysUser";

import UpdateForm from './components/UpdateForm';
import CreateForm from './components/CreateForm';
import {
  FormOutlined,
  DeleteOutlined,
} from '@ant-design/icons';

const actionRef = createRef();

class SysUser extends Component {
  constructor(props) {
    super(props)
    this.state = {
      createModalVisible: false,
      updateModalVisible: false,
      selectRow: {},
      roleList: [],
      RoleOptions: [],
    }
    BaseRoleList({
      limit: 100,
      page: 1,
    }).then(({ result, success }) => {
      if (!success) {
        return;
      }
      const roleList = result.arr;
      const RoleOptions = roleList.map(item => ({ label: item.roleName, value: item.id }));
      this.setState({
        roleList,
        RoleOptions,
      })
    })
  }

  async handleDeal({ fields, serviceMethod, type = "添加" }) {
    const hide = message.loading(`正在${type}`);
    try {
      const res = await serviceMethod(fields);
      hide();
      if (!res.success) {
        message.error(`${type}失败，${res.result}`);
        return false;
      }
      message.success(`${type}成功`);
      return true;
    } catch (error) {
      hide();
      message.error(`${type}异常，${error}`);
      return false;
    }
  }

  async getDataSource(params) {
    const { result, success } = await UserList({
      ...params,
      page: params.current,
      limit: params.pageSize,
    })
    if (!success) {
      return {
        data: [],
        page: 1,
        success: false,
        total: 0,
      };
    }
    return {
      data: result.arr,
      page: 1,
      success: true,
      total: result.count,
    };
  }
  createColumns() {
    return [
      {
        title: '用户名',
        dataIndex: 'userName',
        rules: [{
          required: true,
        }],
      },
      {
        title: '密码',
        dataIndex: 'pwd',
        rules: [{
          required: true,
        }],
        hideInSearch: true,
        hideInTable: true,
      },
      {
        title: '显示名',
        dataIndex: 'trueName',
        rules: [{
          required: true,
        }],
      },
      {
        title: '是否可用',
        dataIndex: 'isEnable',
        valueEnum: {
          [false]: {
            text: '禁用',
            status: 'Default',
          },
          [true]: {
            text: '启用',
            status: 'Success',
          },
        },
      },
      {
        title: '创建者',
        dataIndex: 'fuserName',
        hideInForm: true,
      },
      {
        title: '类型',
        dataIndex: 'userType',
        hideInTable: true,
        valueEnum: {
          0: {
            text: '管理员',
          },
          1: {
            text: `普通用户`,
          },
        },
      },
      // {
      //   title: '备注',
      //   dataIndex: 'remark',
      // },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        valueType: 'dateTime',
        hideInForm: true,
      },
      {
        title: '页面权限',
        dataIndex: 'authority',
        hideInTable: true,
      },
      {
        title: '角色',
        dataIndex: 'roles',
        hideInForm: true,
        width: 300,
        ellipsis: true,
      },
      {
        title: '角色',
        dataIndex: 'roleIdList',
        hideInTable: true,
        renderFormItem: (item, { defaultRender, ...rest }, form) => {
          return (<Select mode="multiple" options={this.state.RoleOptions} />)
        }
      },
      {
        title: '操作',
        dataIndex: 'option',
        valueType: 'option',
        render: (_, row) => (
          <Space>
            <Button
              onClick={async (e) => {
                e.stopPropagation();
                const hide = message.loading('正在载入');
                try {
                  const res = await UserRoleList({ id: row.id, page: 1, limit: 100, });
                  hide();
                  if (!res.success) {
                    message.error(`载入失败，${res.result}`);
                    return;
                  }
                  const selectRow = {
                    ...row,
                    userType: row.userType.toString(),
                    isEnable: row.isEnable.toString(),
                    roleIdList: res.result.arr.map(item => item.roleId),
                  }
                  this.setState({
                    updateModalVisible: true,
                    selectRow,
                  })
                  message.success('载入成功');
                } catch (error) {
                  hide();
                  message.error(`载入异常，${error}`);
                  return;
                }


              }}
              size="small" type="primary" icon={<FormOutlined />} ></Button>
            <Button
              onClick={(e) => {
                e.stopPropagation();
                Modal.confirm({
                  title: '是否确认删除?',
                  icon: <ExclamationCircleOutlined />,
                  onOk: async () => {
                    const idList = {
                      "id": [
                        row.id
                      ]
                    };
                    const success = await this.handleDeal({
                      type: "删除",
                      fields: idList,
                      serviceMethod: UserDel
                    });
                    if (!success) {
                      return;
                    }
                    if (!actionRef.current) {
                      return;
                    }
                    actionRef.current.reload();
                  },
                });
              }}
              size="small" type="primary" icon={<DeleteOutlined />}></Button>
          </Space>
        ),
      },
    ];
  }

  render() {
    return (
      <PageHeaderWrapper>
        <MotionLayout>
          <ProTable
            actionRef={actionRef}
            headerTitle=""

            rowKey="id"
            params={{}}
            request={async (params) => this.getDataSource(params)}
            columns={this.createColumns()}
            rowSelection={{}}
            pagination={{
              pageSize: 10,
            }}
            search={false}
            toolBarRender={(action, { selectedRowKeys, selectedRows }) => [
              <Button type="primary"
                onClick={() => {
                  const selectRow = {
                    userType: "0",
                    isEnable: "true",
                  }
                  this.setState({
                    createModalVisible: true,
                    selectRow,
                  })
                }}
              >
                <PlusOutlined /> 新建
                              </Button>,
              selectedRowKeys && selectedRowKeys.length > 0 && (
                <Dropdown
                  overlay={
                    <Menu
                      onClick={async e => {
                        if (e.key === 'remove') {
                          const idList = {
                            "id": selectedRowKeys
                          };
                          Modal.confirm({
                            title: '是否确认删除?',
                            icon: <ExclamationCircleOutlined />,
                            onOk: async () => {
                              const success = await this.handleDeal({
                                type: "删除",
                                fields: idList,
                                serviceMethod: UserDel
                              });
                              if (!success) {
                                return;
                              }
                              if (!actionRef.current) {
                                return;
                              }
                              actionRef.current.reload();
                            },
                          });
                        }
                      }}
                      selectedKeys={[]}
                    >
                      <Menu.Item key="remove">批量删除</Menu.Item>
                      <Menu.Item key="approval">批量审批</Menu.Item>
                    </Menu>
                  }
                >
                  <Button>
                    批量操作 <DownOutlined />
                  </Button>
                </Dropdown>
              ),
            ]}
          />
        </MotionLayout>
        <CreateForm
          onCancel={() => this.setState({ createModalVisible: false })}
          createModalVisible={this.state.createModalVisible}
        >
          <ProTable
            onSubmit={async fieldsValues => {
              const fields = {
                ...fieldsValues,
                userType: Number(fieldsValues.userType),
                isEnable: fieldsValues.isEnable == "true",
                roles: fieldsValues.roleIdList == undefined ? "" : this.state.RoleOptions.filter(item => fieldsValues.roleIdList.some(sitem => sitem == item.value)).map(item => item.label).join(','),
              }
              const hide = message.loading(`正在添加`);
              try {
                const resUser = await UserAdd(fields);
                hide();
                if (!resUser.success) {
                  message.error(`添加失败，${resUser.result}`);
                  return;
                }
                //没有值就不添加
                if (!(fieldsValues.roleIdList == undefined || fieldsValues.roleIdList.length == 0)) {
                  const resUserRole = await UserRoleAdd({
                    id: resUser.result.id,
                    roleIdList: fieldsValues.roleIdList,
                  });
                  if (!resUserRole.success) {
                    message.error(`添加失败，${resUserRole.result}`);
                    return;
                  }
                }
                message.success(`添加成功`);
                this.setState({
                  createModalVisible: false,
                })
                if (!actionRef.current) {
                  return;
                }
                actionRef.current.reload();
              } catch (error) {
                hide();
                message.error(`添加异常，${error}`);
                return false;
              }
            }}
            rowKey="id"
            type="form"
            form={{
              initialValues: {
                ...this.state.selectRow,
              }
            }}
            columns={this.createColumns()}
          />
        </CreateForm>
        <UpdateForm
          onCancel={() => this.setState({ updateModalVisible: false })}
          updateModalVisible={this.state.updateModalVisible}
        >
          <ProTable
            onSubmit={async fieldsValues => {
              const fields = {
                ...fieldsValues,
                userType: Number(fieldsValues.userType),
                isEnable: fieldsValues.isEnable == "true",
                id: this.state.selectRow.id,
                roles: this.state.RoleOptions.filter(item => fieldsValues.roleIdList.some(sitem => sitem == item.value)).map(item => item.label).join(','),
              }
              const success = await this.handleDeal({
                type: "更新",
                fields,
                serviceMethod: UserEditWithRole,
              });
              if (!success) {
                return;
              }
              this.setState({
                updateModalVisible: false,
              })
              if (!actionRef.current) {
                return;
              }
              actionRef.current.reload();
            }}
            rowKey="id"
            type="form"
            form={{
              initialValues: {
                ...this.state.selectRow,
              }
            }}
            columns={this.createColumns()}
          />
        </UpdateForm>
      </PageHeaderWrapper>
    )
  }
}
export default SysUser
